<template>
  <div class="exam-progress-container">
    <!-- 顶部导航 -->
    <div class="header">
      <van-icon name="arrow-left" class="back-icon" @click="navigateBack" />
      <h1 class="title">答题进度</h1>
      <div class="timer">
        <van-icon name="clock" size="16" class="timer-icon" />
        <span class="timer-text">{{ timer }}</span>
      </div>
    </div>

    <!-- 答题统计 -->
    <div class="stats-container">
      <div class="stat-item">
        <div class="stat-number">{{ answeredCount }}</div>
        <div class="stat-label">已答题</div>
      </div>
      <div class="stat-item">
        <div class="stat-number">{{ totalCount - answeredCount }}</div>
        <div class="stat-label">未答题</div>
      </div>
      <div class="stat-item">
        <div class="stat-number">{{ markedCount }}</div>
        <div class="stat-label">已标记</div>
      </div>
    </div>

    <!-- 题目导航 -->
    <div class="question-navigation">
      <h2 class="section-title">题目导航</h2>
      <div class="question-grid">
        <div
          v-for="i in totalCount"
          :key="i"
          class="question-item"
          :class="{
            'answered': answeredQuestions.includes(i),
            'current': currentQuestion === i,
            'marked': markedQuestions.includes(i),
            'unanswered': !answeredQuestions.includes(i)
          }"
          @click="navigateToQuestion(i)"
        >
          {{ i }}
        </div>
      </div>
    </div>

    <!-- 图例说明 -->
    <div class="legend-container">
      <div class="legend-item">
        <div class="legend-color answered"></div>
        <div class="legend-text">已答题</div>
      </div>
      <div class="legend-item">
        <div class="legend-color current"></div>
        <div class="legend-text">当前题</div>
      </div>
      <div class="legend-item">
        <div class="legend-color marked"></div>
        <div class="legend-text">已标记</div>
      </div>
      <div class="legend-item">
        <div class="legend-color unanswered"></div>
        <div class="legend-text">未答题</div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <van-button
        type="default"
        block
        size="large"
        class="continue-button"
        @click="continueAnswering"
      >
        继续答题
      </van-button>
      <van-button
        type="danger"
        block
        size="large"
        class="submit-button"
        @click="submitExam"
      >
        提交考试
      </van-button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { submitExam, saveExamDraft } from '@/api/examApi'

export default {
  name: 'ExamProgress',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const examId = ref(route.params.id)
    const totalCount = ref(0)
    const answeredCount = ref(0)
    const markedCount = ref(0)
    const currentQuestion = ref(1)
    const answeredQuestions = ref([])
    const markedQuestions = ref([])
    const timer = ref('01:23:45')
    const timerInterval = ref(null)
    const answers = ref({})

    // 开始计时器
    const startTimer = () => {
      // 简化的计时器实现
      let seconds = 5025 // 1小时23分45秒
      timerInterval.value = setInterval(() => {
        seconds--
        if (seconds <= 0) {
          clearInterval(timerInterval.value)
          // 时间到，自动提交
          submitExamAction()
          return
        }

        const hours = Math.floor(seconds / 3600)
        const minutes = Math.floor((seconds % 3600) / 60)
        const remainingSeconds = seconds % 60

        timer.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      }, 1000)
    }

    // 导航回上一页
    const navigateBack = () => {
      router.go(-1)
    }

    // 导航到题目
    const navigateToQuestion = (questionNumber) => {
      // 在实际项目中，这里应该导航到具体的题目页面
      currentQuestion.value = questionNumber
      Toast(`跳转到第${questionNumber}题`)
    }

    // 继续答题
    const continueAnswering = () => {
      // 继续答题，回到当前题目
      Toast('继续答题')
    }

    // 提交考试
    const submitExamAction = () => {
      Dialog.confirm({
        title: '确认提交',
        message: '确定要提交考试吗？提交后将无法修改答案。',
        confirmButtonText: '提交',
        cancelButtonText: '取消'
      }).then(() => {
        // 提交答案
        submitExam(examId.value, {
          answers: answers.value
        }).then(res => {
          if (res.success) {
            Toast('考试提交成功')
            router.push(`/exam/${examId.value}/result`)
          } else {
            Toast('提交失败，请重试')
          }
        }).catch(err => {
          Toast('提交失败，请重试')
          console.error('提交考试失败:', err)
        })
      }).catch(() => {
        // 取消提交
      })
    }

    // 保存草稿
    const saveDraft = () => {
      saveExamDraft(examId.value, {
        answers: answers.value,
        markedQuestions: markedQuestions.value
      }).then(res => {
        if (res.success) {
          Toast('草稿保存成功')
        } else {
          Toast('保存失败，请重试')
        }
      }).catch(err => {
        Toast('保存失败，请重试')
        console.error('保存草稿失败:', err)
      })
    }

    // 初始化
    onMounted(() => {
      // 在实际项目中，这里应该从服务器获取考试数据
      totalCount.value = 50
      answeredCount.value = 5
      markedCount.value = 2
      answeredQuestions.value = [1, 2, 3, 4, 5]
      markedQuestions.value = [3, 7]
      startTimer()
    })

    // 组件卸载前清除计时器
    onBeforeUnmount(() => {
      if (timerInterval.value) {
        clearInterval(timerInterval.value)
      }
    })

    return {
      totalCount,
      answeredCount,
      markedCount,
      currentQuestion,
      answeredQuestions,
      markedQuestions,
      timer,
      navigateBack,
      navigateToQuestion,
      continueAnswering,
      submitExam: submitExamAction,
      saveDraft
    }
  }
}
</script>

<style scoped>
.exam-progress-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-icon {
  color: white;
  font-size: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: white;
}

.timer {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 5px 10px;
  border-radius: 15px;
}

.timer-icon {
  color: white;
  margin-right: 5px;
}

.timer-text {
  font-size: 14px;
  color: white;
}

.stats-container {
  background-color: white;
  padding: 15px;
  margin: 15px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #667eea;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.question-navigation {
  background-color: white;
  padding: 15px;
  margin: 0 15px 15px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.question-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.question-item {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  background-color: #e5e5e5;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.question-item.answered {
  background-color: #4cd964;
  color: white;
}

.question-item.current {
  background-color: #667eea;
  color: white;
  border: 2px solid #3a57e8;
}

.question-item.marked {
  background-color: #ffcc00;
  color: white;
}

.question-item.unanswered {
  background-color: #e5e5e5;
  color: #666;
}

.legend-container {
  background-color: white;
  padding: 15px;
  margin: 0 15px 15px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  margin-right: 6px;
}

.legend-color.answered {
  background-color: #4cd964;
}

.legend-color.current {
  background-color: #667eea;
}

.legend-color.marked {
  background-color: #ffcc00;
}

.legend-color.unanswered {
  background-color: #e5e5e5;
}

.legend-text {
  font-size: 12px;
  color: #666;
}

.action-buttons {
  padding: 0 15px;
  margin-top: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.continue-button {
  background-color: #667eea;
}

.submit-button {
  background-color: #ff3b30;
}
</style>